<template>
	<div :style="{ width: '100%', height: '100%' }">
		<div
			:id="containId"
			:style="{ width: containSize.width, height: containSize.height }"
			class="container"
		></div>
		<div class="map_search" :id="mapsearchId">
			<label id="tipinput_label" for="tipinput" class="search_label"
			>地址查询:
			</label>
			<!-- <el-input v-for="item in tipinputs" :key="item.tipinputId" :id="item.tipinputId" v-model="tipinput" class="search_input" /> -->
<!--			<el-input id="tipinputId" v-model="tipinput" class="search_input" ref="searchInput"/>-->
			<el-input :id="tipinputId" v-model="tipinput" clearable class="search_input" ref="searchInput"/>
			<!-- <el-button type="primary" class="mapbtn_sear" @click="addSearch" plain
			><i-ep-search />查询</el-button
		> -->
			<el-button type="" class="mapbtn_close" @click="mapHide" text
			>
				<i-ep-close/>
				关闭
			</el-button
			>
		</div>
	</div>
</template>

<script lang="ts" setup>
import iconMark from "@/assets/map/map-marker.png";
import {nextTick} from "vue";

interface containSizeType {
	width: string;
	height: string;
}

let props = defineProps({
	containSize: {
		type: Object,
		default: () => ({width: "400px", height: "300px"}),
	},
	prevPoint: {
		type: Object,
		default: () => ({lat: 29.641156373429688, lng: 91.13585449304729}),
	},
	containId: {
		type: String,
		default: () => "contain",
	},
});

let prevPoint = props.prevPoint;
let tipinput = ref("");
const options = ref([]);
const loading = ref(false);

let currentPoint: {
	lat: Number;
	lng: Number;
};
let map; //地图
let marker; //点标记
let autoComplete;
let myIcon;
const tipinputId = ref(GenNonDuplicateID());
const mapsearchId = ref(GenNonDuplicateID());
const searchInput = ref();

const emit = defineEmits(["sendProjectPoint", "sendProjectAddr", "mapHide"]);

function GenNonDuplicateID() {
	let idStr = Date.now().toString(36)
	idStr += Math.random().toString(36).substr(3)
	return idStr
}

onMounted(() => {
	currentPoint = prevPoint;
	init();
});

onUnmounted(() => {
	destroyMap();
});

function remoteMethod(query) {
	if(query){
		loading.value = true;
		// autoComplete.setInputValue(query);
		autoComplete.search(query)
	}
}

function mapHide() {
	emit("mapHide");
}

function destroyMap() {
	// map.off("click", getLatLng);
	clearMarker();
	tipinput.value = '';
	if (autoComplete) {
		autoComplete.hide();
		autoComplete.dispose();
		autoComplete = null;
	}
	if (map) {
		map.destroy();
		map = null;
	}
}

async function init() {
	// if (!map) {
	/* 注册map */
	map = new BMapGL.Map(props.containId);
	let point = new BMapGL.Point(currentPoint.lng, currentPoint.lat);
	map.centerAndZoom(point, 13);
	map.enableScrollWheelZoom(true);
	// 添加比例尺控件
	var scaleCtrl = new window.BMapGL.ScaleControl();
	map.addControl(scaleCtrl);
	// 添加缩放控件
	var zoomCtrl = new window.BMapGL.ZoomControl();
	map.addControl(zoomCtrl);
	// 添加城市列表控件
	var cityCtrl = new window.BMapGL.CityListControl();
	map.addControl(cityCtrl);
	
	/* 注册单击事件 */
	map.addEventListener("click", getLatLng);
	
	// addMarker(currentPoint);
	// searchAddress();
	// }
}

function addSearch() {
}

function G(id) {
	return document.getElementById(id);
}

async function searchAddress() {
	searchInput.value.ref.id = GenNonDuplicateID();
	
	if (!autoComplete) {
		autoComplete = new BMapGL.Autocomplete({
			//建立一个自动完成的对象
			input: `${searchInput.value.ref.id}`,
			// input: 'tipinputId',
			location: map,
		});
		
		autoComplete.addEventListener("onhighlight", function (e) {
			//鼠标放在下拉列表上的事件
			var str = "";
			var _value = e.fromitem.value;
			var value = "";
			if (e.fromitem.index > -1) {
				value =
					_value.province +
					_value.city +
					_value.district +
					_value.street +
					_value.business;
			}
			str =
				"FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

			value = "";
			if (e.toitem.index > -1) {
				_value = e.toitem.value;
				value =
					_value.province +
					_value.city +
					_value.district +
					_value.street +
					_value.business;
			}
			str +=
				"<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
			// G("searchResultPanel").innerHTML = str;
		});

		var addr;
		autoComplete.addEventListener("onconfirm", function (e) {
			//鼠标点击下拉列表后的事件
			var _value = e.item.value;
			addr =
				_value.province +
				_value.city +
				_value.district +
				_value.street +
				_value.business;

			// G("searchResultPanel").innerHTML =
			//   "onconfirm<br />index = " + e.item.index + "<br />addr = " + addr;

			setPlace();
		});
		
		function setPlace() {
			map.clearOverlays(); //清除地图上所有覆盖物
			function myFun() {
				var pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
				emit("sendProjectPoint", pp);
				emit("sendProjectAddr", addr);
				map.centerAndZoom(pp, 18);
				map.addOverlay(new BMapGL.Marker(pp, {icon: myIcon})); //添加标注
			}
			
			var local = new BMapGL.LocalSearch(map, {
				//智能搜索
				onSearchComplete: myFun,
			});
			local.search(addr);
		}
	}
}

/* 地图点击事件 */
function getLatLng(point) {
	currentPoint.lat = point.latlng.lat;
	currentPoint.lng = point.latlng.lng;
	addMarker(currentPoint);
	emit("sendProjectPoint", currentPoint);
}

/* 添加点标记 */
function addMarker(point) {
	clearMarker();
	
	var gc = new BMapGL.Geocoder();
	var new_point = new BMapGL.Point(currentPoint.lng, currentPoint.lat);
	gc.getLocation(new_point, function (rs) {
		var addComp = rs.addressComponents;
		// //获取详细的地址，精确到街道的名称
		var addrname =
			addComp.city + addComp.district + addComp.street + addComp.streetNumber;
		emit("sendProjectAddr", addrname);
	});
	if (BMapGL) {
		myIcon = new BMapGL.Icon(iconMark, new BMapGL.Size(23, 25), {
			// 指定定位位置。
			// 当标注显示在地图上时，其所指向的地理位置距离图标左上
			// 角各偏移10像素和25像素。您可以看到在本例中该位置即是
			// 图标中央下端的尖角位置。
			// anchor: new BMapGL.Size(45, 45),
			// 设置图片偏移。
			// 当您需要从一幅较大的图片中截取某部分作为标注图标时，您
			// 需要指定大图的偏移位置，此做法与css sprites技术类似。
			// imageOffset: new BMapGL.Size(0, 0 - 25)   // 设置图片偏移
		});
		// 创建标注对象并添加到地图
		marker = new BMapGL.Marker(point, {icon: myIcon});
		map.addOverlay(marker);
	}
}

// 设置中心点
function setCenter(point) {
	if (map) {
		map.centerAndZoom(point, 13);
	}
}

// 清除 marker
function clearMarker() {
	if (marker) marker.remove();
	if (map) map.clearOverlays();
}

function clearMap() {
	map.removeEventListener("click", getLatLng);
}

defineExpose({
	destroyMap,
	addMarker,
	setCenter,
	searchAddress,
	init,
});
</script>

<style lang="scss" scoped>
.container {
	position: relative;
	margin: 35px 20px 20px 20px;
	border-radius: 10px;
	z-index: 0;
}

.search_input {
	width: 200px;
	height: 22px;
	line-height: 22px;
	// border: 1px solid #a5a5a5 !important;
	font-size: 13px;
	color: #181818;
	z-index: 9999;
}

.search_label {
	width: 120px;
	font-size: 12px;
	color: #797878;
}

.map_search {
	position: absolute;
	top: 10px;
	left: 20px;
	width: 100%;
	z-index: 9999;
}

.tangram-suggestion-main {
	z-index: 9999;
}

.mapbtn_sear {
	height: 22px;
	line-height: 22px;
	font-size: 13px;
	margin-left: 5px;
}

.mapbtn_close {
	height: 32px;
	line-height: 32px;
	font-size: 13px;
	position: absolute;
	right: 20px;
	top: -10px;
}
</style>
